package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class GoodsService {

    private SpuMapper spuMapper;

    private SpuDetailMapper detailMapper;

    public GoodsService(SpuMapper spuMapper, SpuDetailMapper detailMapper, CategoryService categoryService, BrandService brandService, SkuMapper skuMapper) {
        this.spuMapper = spuMapper;
        this.detailMapper = detailMapper;
        this.categoryService = categoryService;
        this.brandService = brandService;
        this.skuMapper = skuMapper;
    }

    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        // 1.分页
        Page<Spu> info = PageHelper.startPage(page, rows);

        // 2.构建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 2.1.过滤条件
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.2.上下架过滤
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 2.3.排序
        example.setOrderByClause("update_time DESC");

        // 3.查询
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        // 4.封装结果
        // 4.1.处理DTO
        List<SpuDTO> dtoList = BeanHelper.copyWithCollection(list, SpuDTO.class);
        // 4.2.处理分类和品牌的名称
        handleCategoryAndBrandName(dtoList);

        return new PageResult<>(info.getTotal(), info.getPages(), dtoList);
    }

    private CategoryService categoryService;

    private BrandService brandService;

    private void handleCategoryAndBrandName(List<SpuDTO> dtoList) {
        for (SpuDTO spuDTO : dtoList) {
            // 根据品牌id查询品牌
            BrandDTO brand = brandService.queryById(spuDTO.getBrandId());
            spuDTO.setBrandName(brand.getName());
            // 根据分类id的集合查询分类集合
            /*List<CategoryDTO> categoryList = categoryService.queryByIds(spuDTO.getCategoryIds());
            StringBuilder sb = new StringBuilder();
            for (CategoryDTO categoryDTO : categoryList) {
                sb.append(categoryDTO.getName()).append("/");
            }
            sb.deleteCharAt(sb.length() - 1);*/
            String name = categoryService.queryByIds(spuDTO.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spuDTO.setCategoryName(name);
        }
    }

    private SkuMapper skuMapper;

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        // 1.保存spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 默认商品下架
        spu.setSaleable(false);
        spuMapper.insertSelective(spu);

        long spuId = spu.getId();
        // 2.保存spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail detail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        detail.setSpuId(spuId);
        detailMapper.insertSelective(detail);

        // 3.保存sku
        saveSku(spuDTO, spuId);
    }

    private void saveSku(SpuDTO spuDTO, long spuId) {
        List<SkuDTO> list = spuDTO.getSkus();
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : list) {
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setEnable(false);
            sku.setSpuId(spuId);
            skuList.add(sku);
        }
        // 批量保存
        skuMapper.insertList(skuList);
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        // 1.更新spu
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        spuMapper.updateByPrimaryKeySelective(spu);

        // 2.更新sku
        // 2.1.要更新的数据
        Sku sku = new Sku();
        sku.setEnable(saleable);
        // 2.2.更新的条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        skuMapper.updateByExampleSelective(sku, example);

        // 发送消息，通知其它服务，商品完成上架或下架
        String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY : MQConstants.RoutingKey.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, id);
    }


    public SpuDTO querySpuById(Long spuId) {
        // 1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);

        // 2.查询spuDetail
        spuDTO.setSpuDetail(querySpuDetailBySpuId(spuId));

        // 3.查询sku
        spuDTO.setSkus(querySkuBySpuId(spuId));

        return spuDTO;
    }

    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> list = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    public SpuDetailDTO querySpuDetailBySpuId(Long spuId) {
        SpuDetail detail = detailMapper.selectByPrimaryKey(spuId);
        if (detail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(detail, SpuDetailDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        // 1.修改spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 把不需要修改的字段设置未null，避免修改该字段
        spu.setSaleable(null);
        spuMapper.updateByPrimaryKeySelective(spu);

        // 2.修改spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail detail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        detailMapper.updateByPrimaryKeySelective(detail);

        // 3.删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuDTO.getId());
        skuMapper.delete(sku);

        // 4.新增sku
        saveSku(spuDTO, spuDTO.getId());
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> numMap) {
        for (Map.Entry<Long, Integer> entry : numMap.entrySet()) {
            // 减库存
            skuMapper.minusStock(entry.getKey(), entry.getValue());
        }
    }
}
